package com.comdo.newup_loan.module.myinfo;

import android.app.Activity;
import android.os.AsyncTask;

import com.comdo.newup_loan.R;
import com.comdo.newup_loan.bank.BankUtils;
import com.comdo.newup_loan.bank.bank.BankApiManager;
import com.comdo.newup_loan.comom.Config;
import com.comdo.newup_loan.http.RetrofitHelper;
import com.comdo.newup_loan.model.NativeBean;
import com.comdo.newup_loan.model.Result;
import com.comdo.newup_loan.model.UpLoadCard;
import com.comdo.newup_loan.model.UserBaseInfo;
import com.comdo.newup_loan.util.BitmapUtil;
import com.comdo.newup_loan.util.StringUtils;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Response;

/**
 * Created by liyuan on 2017/10/30.
 */

class MyInfoPresenter extends MyInfoContract.Presenter {
    @Override
    public void getInfo(int userId) {
        Gson gson = new Gson();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("token", Config.loginInfo.getToken());
        map.put("sign", StringUtils.SortStringAndAddKey(map));
        String strEntity = gson.toJson(map);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        mCompositeDisposable.add(RetrofitHelper.createMyApi().getBaseInfo(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<UserBaseInfo>>() {
                    @Override
                    public void accept(Result<UserBaseInfo> Result) throws Exception {
                        if (Result.getCode() == 1) {
                            mView.getBaseInfo(Result.getResult());
                        } else if (Result.getCode() == -3) {
                            mView.exitLogin();
                            mView.Fail(Result.getMessage());
                        } else {
                            mView.Fail(Result.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mView.Fail("请求失败！");
                    }
                }));
    }

    @Override
    public void saveInfo(int userId, UserBaseInfo userBaseInfo) {
        Gson gson = new Gson();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        if (StringUtils.isNull(userBaseInfo.getIdentityCardFront())) {
            map.put("identityCardFront", -1);
        } else {
            map.put("identityCardFront", userBaseInfo.getIdentityCardFront());
        }
        if (StringUtils.isNull(userBaseInfo.getIdentityCardReverse())) {
            map.put("identityCardReverse", -1);
        } else {
            map.put("identityCardReverse", userBaseInfo.getIdentityCardReverse());
        }
        if (StringUtils.isNull(userBaseInfo.getSex())) {
            map.put("sex", -1);
        } else {
            map.put("sex", userBaseInfo.getSex());
        }
        if (StringUtils.isNull(userBaseInfo.getCityId())) {
            map.put("cityId", -1);
        } else {
            map.put("cityId", userBaseInfo.getCityId());
        }
        map.put("email", userBaseInfo.getEmail());
        map.put("industrycategoryId", userBaseInfo.getIndustrycategoryId()+"");
        map.put("liabilities", userBaseInfo.getLiabilitiesId()+"");
        map.put("income", userBaseInfo.getIncomeId()+"");
        map.put("token", Config.loginInfo.getToken());
        map.put("sign", StringUtils.SortStringAndAddKey(map));
        String strEntity = gson.toJson(map);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        mCompositeDisposable.add(RetrofitHelper.createMyApi().saveBaseInfo(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<String>>() {
                    @Override
                    public void accept(Result<String> Result) throws Exception {
                        if (Result.getCode() == 1) {
                            mView.saveInfo(Result.getResult());
                        } else if (Result.getCode() == -3) {
                            mView.Fail(Result.getMessage());
                            mView.exitLogin();
                        } else {
                            mView.Fail(Result.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mView.Fail("请求失败！");
                    }
                }));
    }

    @Override
    public void getNativePlace() {
        mCompositeDisposable.add(RetrofitHelper.createMyApi().getNativePlace()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<List<NativeBean>>>() {
                    @Override
                    public void accept(Result<List<NativeBean>> Result) throws Exception {
                        if (Result.getCode() == 1) {
                            mView.getNativePlace(Result.getResult());
                        } else if (Result.getCode() == -3) {
                            mView.Fail(Result.getMessage());
                            mView.exitLogin();
                        } else {
                            mView.Fail(Result.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mView.Fail("请求失败！");
                    }
                }));
    }

    @Override
    public void upLoad(final int id, final String filePath, final int cardType) {
        new AsyncTask<Integer, Integer, File>() {
            @Override
            protected File doInBackground(Integer... params) {
                //压缩图片
                File file = new File(BitmapUtil.compressImage(filePath));
                return file;
            }

            @Override
            protected void onPostExecute(File file) {
                super.onPostExecute(file);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("userId", id);
                map.put("token", Config.loginInfo.getToken());
                map.put("type", cardType);
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part fileBody =
                        MultipartBody.Part.createFormData("files[]", file.getName(), requestFile);
                MultipartBody.Part userId =
                        MultipartBody.Part.createFormData("userId", String.valueOf(id));
                MultipartBody.Part token =
                        MultipartBody.Part.createFormData("token", Config.loginInfo.getToken());
                MultipartBody.Part type =
                        MultipartBody.Part.createFormData("type", String.valueOf(cardType));
                MultipartBody.Part sign =
                        MultipartBody.Part.createFormData("sign", StringUtils.SortStringAndAddKey(map));
                mView.showLoadingDialog("");
                mCompositeDisposable.add(RetrofitHelper.createMyApi().imageUploadCard(fileBody, userId, type, token, sign)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Result<UpLoadCard>>() {
                            @Override
                            public void accept(Result<UpLoadCard> Result) throws Exception {
                                mView.dismissLoadingDialog();
                                if (Result.getCode() == 1) {
                                    mView.upLoad(Result.getResult());
                                } else {
                                    mView.Fail(Result.getMessage());
                                }
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                mView.dismissLoadingDialog();
                                mView.Fail("请求失败");
                            }
                        }));
            }
        }.execute();
    }

    @Override
    public void changeCard(int userId) {
        Gson gson = new Gson();
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("token", Config.loginInfo.getToken());
        map.put("sign", StringUtils.SortStringAndAddKey(map));
        String strEntity = gson.toJson(map);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        mCompositeDisposable.add(RetrofitHelper.createMyApi().changeBankCard(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<String>>() {
                    @Override
                    public void accept(Result<String> Result) throws Exception {
                        if (Result.getCode() == 1) {
                            mView.changeCard(Result.getResult());
                        } else if (Result.getCode() == -3) {
                            mView.Fail(Result.getMessage());
                            mView.exitLogin();
                        } else {
                            mView.Fail(Result.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }));
    }

    @Override
    public void getXwWeb(Activity tag) {
        FormBody body = BankApiManager.getIstance().replaceCard(tag, BankUtils.createRequestNo());
        mView.showLoadingDialog(tag.getResources().getString(R.string.xw_request_str));
        mCompositeDisposable.add(RetrofitHelper.createMyBankApi().getWebUrl(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Response<String>>() {
                    @Override
                    public void accept(Response<String> Result) throws Exception {
                        mView.dismissLoadingDialog();
                        mView.getXwWeb(Result.headers().get("Location"));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ;
                        mView.dismissLoadingDialog();
                        mView.Fail("请求失败" + throwable.getMessage());
                    }
                }));
    }
}
